package com.liu.my_blog_system.config;

import com.liu.my_blog_system.entity.TbUser;
import com.liu.my_blog_system.service.TbUserService;
import com.liu.my_blog_system.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author liuchengjie
 */
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private TbUserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查是否是管理员
        Map map = userService.checkUserStatus(request, response);
        TbUser userInfo = (TbUser)map.get("userInfo");
        if (!ObjectUtils.isEmpty(userInfo) && userInfo.getRoles().equals(Constants.User.ADMIN)) {
            return true;
        }
        //todo:权限不足返回到登录页面
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
